<template>
    <!-- 主要内容区域 -->
    <div class="flex-1 p-6 overflow-auto bg-gray-100">
        <div class="bg-white rounded-lg p-6">
            <!-- 搜索区域 -->
            <div class="flex items-center space-x-4 mb-6">
                <el-input v-model="searchForm.keyword" placeholder="请输入部门名称" class="w-64" clearable>
                    <template #prefix>
                        <el-icon>
                            <Search />
                        </el-icon>
                    </template>
                </el-input>
                <el-input v-model="searchForm.username" placeholder="请输入角色" class="w-64" clearable>
                </el-input>
                <el-input v-model="searchForm.phone" placeholder="请输入手机号码" class="w-64" clearable>
                </el-input>
                <el-select v-model="searchForm.status" placeholder="用户状态" class="w-32">
                    <el-option label="全部" value="" />
                    <el-option label="启用" value="1" />
                    <el-option label="禁用" value="0" />
                </el-select>
                <el-button type="primary" class="!rounded-button" @click="handleSearch">
                    <el-icon class="mr-1">
                        <Search />
                    </el-icon>搜索
                </el-button>
                <el-button class="!rounded-button" @click="handleReset">
                    <el-icon class="mr-1">
                        <Refresh />
                    </el-icon>重置
                </el-button>
            </div>
            <!-- 操作按钮 -->
            <div class="flex justify-between mb-4">
                <div class="space-x-2">
                    <el-button type="primary" class="!rounded-button" @click="openDialog('add')">
                        <el-icon class="mr-1">
                            <Plus />
                        </el-icon>新增
                    </el-button>
                    <el-button type="danger" class="!rounded-button whitespace-nowrap" @click="handleDelete">
                        <el-icon class="mr-1">
                            <Delete />
                        </el-icon>删除
                    </el-button>
                    <el-button type="success" class="!rounded-button" @click="handleImport">
                        <el-icon class="mr-1">
                            <Upload />
                        </el-icon>导入
                    </el-button>
                    <el-button type="warning" class="!rounded-button" @click="handleExport">
                        <el-icon class="mr-1">
                            <Download />
                        </el-icon>导出
                    </el-button>
                </div>
            </div>
            <!-- 表格 -->
            <el-table :data="tableData" border stripe  @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column label="招聘方编号" prop="id" width="120" />
                <el-table-column label="姓名" prop="userName" width="120" />
                <el-table-column label="性别" prop="gender" width="80" >
                    <template v-slot="scope">
                        {{ scope.row.gender === 0 ? '男' : '女' }}
                    </template>
                </el-table-column>
                <el-table-column label="公司" prop="company" width="120" />
                <el-table-column label="所处岗位" prop="position" width="120" />
                <el-table-column label="封禁" prop="close" width="100">
                <template #default="scope">
                    <el-switch v-model="scope.row.close" />
                </template>
                </el-table-column>
                <el-table-column label="创建时间" prop="createTime" width="180" :formatter="formatDate"/>
                <el-table-column label="操作" fixed="right" width="180">
                <template #default="scope">
                    <el-button type="primary" link @click="openDialog('edit', scope.row)">修改</el-button>
                    <el-button type="primary" link @click="handleDelete(scope.row)">删除</el-button>
                </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div class="flex justify-end mt-4">
                <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                    :total="pagination.total" :page-sizes="[10, 20, 30, 40]"
                    layout="total, sizes, prev, pager, next, jumper" />
            </div>
        </div>
    </div>


    <!-- 新增/编辑用户弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增招聘方' : '编辑招聘方'" width="500px" destroy-on-close>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="招聘方账号" prop="account">
            <el-input v-model="form.account" placeholder="请输入招聘方账号" />
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.userName" placeholder="请输入姓名" />
          </el-form-item>
            <el-form-item label="性别" prop="gender">
                <el-select
                        v-model="form.gender"
                        placeholder="请选择性别"
                        style="width: 100%"
                >
                    <el-option label="男" :value="0" />
                    <el-option label="女" :value="1" />
                </el-select>
            </el-form-item>
          <el-form-item label="公司" prop="company">
            <el-input v-model="form.company" placeholder="请输入公司" />
          </el-form-item>
          <el-form-item label="所处岗位" prop="position">
            <el-input v-model="form.position" placeholder="请输入所处岗位" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit(formRef)">确认</el-button>
          </span>
        </template>
      </el-dialog>
    <!-- 上传文件弹窗 -->
    <el-upload ref="upload" :action="uploadUrl" :before-upload="beforeUpload" :on-success="handleUploadSuccess"
        :on-error="handleUploadError" accept=".xls,.xlsx" show-file-list="false" :auto-upload="false">
    </el-upload>
</template>

<script lang="ts" setup>
import { ref,reactive,onMounted } from "vue";
import * as XLSX from "xlsx";  // 引入 xlsx 库
import { FormInstance, FormRules, ElMessageBox, ElMessage } from "element-plus";
import {getAllEmployer,updateEmployer,addEmployer,deleteEmployer} from "../../api/admin/userManage.js";
onMounted(()=>{
    getEmployer(pagination.value)
})

// 日期格式化方法
const formatDate = (row, column, cellValue) => {
    if (!cellValue) return '';
    const d = new Date(cellValue);
    return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`; // 返回 yyyy-mm-dd 格式
};


async function getEmployer(data) {
    await getAllEmployer(data).then(function (response) {
            tableData.value=response.items[0]
            pagination.value.total=response.total
        }
    )
}
// 选中的行的ID数组
const selectedRowKeys = ref([]);

const handleSelectionChange = (selection) => {
    selectedRowKeys.value = selection.map(item => item.id);
};

// 重置搜索表单
const handleReset = () => {
  searchForm.value = {
    keyword: "",
    username: "",
    phone: "",
    status: "",
  };
  // 这里可以根据需要重新加载表格数据
};

//搜索栏数据
const searchForm = ref({
    keyword: '',
    username: '',
    phone: '',
    status: '',
    dateRange: [],
});

//表格内容
const tableData = ref([
{
      id: 1,
      name: '李四',
      company: 'ABC公司',
      position: '项目经理',
      isBanned: false,
      createdAt: new Date(),
    },
    {
        id: 2,
        username: '李雪梅',
        nickname: '学生',
        phone: '13912345678',
        account: '2100770045',
        address: 'https://210.47.3.49/1.jpg',
        status: true,
        createTime: '2024-01-15 11:20:00'
    },
    {
        id: 3,
        username: '王建国',
        nickname: 'boss方',
        phone: '13712345678',
        account: '2100770045',
        address: 'https://210.47.3.49/1.jpg',
        status: false,
        createTime: '2024-01-15 14:15:00'
    }
]);

//分页
const pagination = ref({
    currentPage: 1,
    pageSize: 10,
    total: 100
});

// 弹窗相关
const dialogVisible = ref(false);
const dialogType = ref('');
const formRef = ref<FormInstance>();
const form = ref({
    id: '',
    account:'',
    userName: '',
    company: '',
    gender:"",
    position: '',
    close: false,
    createTime: '',
  });

  const rules = {
    id: [{ required: true, message: '请输入招聘方编号', trigger: 'blur' }],
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    company: [{ required: true, message: '请输入公司', trigger: 'blur' }],
    position: [{ required: true, message: '请输入所处岗位', trigger: 'blur' }],
  };

//角色下拉框
const roleOptions = ref([
    { id: 1, name: "管理员" },
    { id: 2, name: "普通用户" },
    { id: 3, name: "学生" }
]);


const openDialog = (type: string, row?: any) => {
    dialogType.value = type;
    if (type === 'edit' && row) {
        // 当前行为编辑模式，填充表单数据
        form.value = {
            account:row.account,
            gedner:row.gender,
            userName: row.userName,
            company: row.company,
            position: row.position,
            id: row.id // 保存当前行的ID以便后续处理
        };
    } else {
        // 清空表单数据
        form.value = {
            account:'',
            gender:'',
            userName: '',
            company: '',
            position: '',
            id: '' // 清空ID
        };
    }
    dialogVisible.value = true;
};
//修改与增加学生
async function add_Employer(data) {
    await addEmployer(data).then(function (response) {
        getEmployer(pagination.value)
    })
}
async function update_Employer(data) {
    await updateEmployer(data).then(function (response) {
        getEmployer(pagination.value)
    })
}
//删除学生
async function delete_Employer(data){
    await deleteEmployer(data).then(function (response) {
        getEmployer(pagination.value)
    })
}
//提交
const handleSubmit = async (formEl: FormInstance | undefined) => {
    if (dialogType.value === 'add') {
        // 处理添加逻辑
        console.log('提交表单 - 添加', form.value);
        add_Employer(form.value)
        ElMessage.success('添加成功');
    } else if (dialogType.value === 'edit') {
        // 处理修改逻辑
        console.log('提交表单 - 修改', form.value);
        update_Employer(form.value)
        ElMessage.success('修改成功');
    }
    dialogVisible.value = false;
};

//删除用户
const handleDelete = (row: any) => {
    // 获取当前选中的行
    const selectedRows = tableData.value.filter(row => selectedRowKeys.value.includes(row.id));

    if (selectedRows.length === 0) {
        ElMessage.warning('请至少选择一项进行删除');
        return;
    }

    ElMessageBox.confirm(
        '确定要删除选中的用户吗？',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        // 模拟删除操作
        selectedRows.forEach(row => {
            tableData.value = tableData.value.filter(item => item.id !== row.id);
        });
        ElMessage.success('删除成功');
    }).catch(() => { });
};


//重置密码
const handleResetPassword = (row: any) => {
    ElMessageBox.confirm(
        '确定要重置该用户的密码吗？',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        console.log('重置密码', row);
        ElMessage.success('密码重置成功');
    }).catch(() => { });
};

// 导入功能
const handleImport = () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.xlsx, .xls';
    input.onchange = (e: any) => {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = (event: any) => {
                const data = event.target.result;
                const wb = XLSX.read(data, { type: 'array' });
                const ws = wb.Sheets[wb.SheetNames[0]];
                const json = XLSX.utils.sheet_to_json(ws, { header: 1 });
                console.log('导入数据:', json);
                // 假设你将数据存入 tableData
                tableData.value = json.slice(1).map((row: any) => {
                    return {
                        id: row[0],
                        username: row[1],
                        nickname: row[2],
                        phone: row[3],
                        account: row[4],
                        address: row[5],
                        status: row[6] === '启用', // 状态转换
                        createTime: row[7]
                    };
                });
                ElMessage.success('文件导入成功');
            };
            reader.readAsArrayBuffer(file);
        }
    };
    input.click();
};

// 导出功能
const handleExport = () => {
    const ws = XLSX.utils.json_to_sheet(tableData.value);  // 将 tableData 转为 sheet
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
    const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
    const data = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = window.URL.createObjectURL(data);
    const link = document.createElement('a');
    link.href = url;
    link.download = '用户数据.xlsx';  // 设置下载的文件名
    link.click();
    ElMessage.success('文件导出成功');
};
</script>

<style scoped></style>